package com.sds.sweng.swat.miplatform.service.viewers;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Node;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;

public class ServiceDetailViewer extends Composite {

	private TableViewer serviceDetail;

	public ServiceDetailViewer(Composite parent) {
		super(parent, SWT.NONE);

		setLayout(new FillLayout());

		init();
	}

	private void init() {
		serviceDetail = new TableViewer(this, SWT.SINGLE | SWT.V_SCROLL | SWT.FULL_SELECTION);
		TableViewerColumn keyColumn = new TableViewerColumn(serviceDetail, SWT.NONE);
		keyColumn.getColumn().setText("Column");
		keyColumn.getColumn().setWidth(100);
		keyColumn.getColumn().setResizable(true);

		TableViewerColumn valueColumn = new TableViewerColumn(serviceDetail, SWT.NONE);
		valueColumn.getColumn().setText("Value");
		valueColumn.getColumn().setWidth(170);
		valueColumn.getColumn().setResizable(true);

		Table table = serviceDetail.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		serviceDetail.setContentProvider(new IStructuredContentProvider() {

			public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
				serviceDetail.refresh(false);
			}

			public void dispose() {
				// do nothing
			}

			public Object[] getElements(Object inputElement) {
				return ((Node) inputElement).selectNodes("*").toArray();
			}
		});

		serviceDetail.setLabelProvider(new ServiceDetailLabelProvider());
	}

	public void setInput(Node serviceRecord) {
		serviceDetail.setInput(serviceRecord);
	}

	public void refresh() {
		serviceDetail.refresh(false);
	}

}

class ServiceDetailLabelProvider extends LabelProvider implements ITableLabelProvider {

	public Image getColumnImage(Object element, int columnIndex) {
		return null;
	}

	public String getColumnText(Object element, int columnIndex) {
		Node serviceDetailRow = (Node) element;

		switch (columnIndex) {
			case 0:
				return serviceDetailRow.getName();
			case 1:
				return serviceDetailRow.getText();
			default:
				return null;
		}
	}

}
